package cn.itcast.chapter05.session.example01;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 18148
 * @Date: 2020-06-05 15:17:24
 */
@WebServlet("/purchaseServlet")
public class PurchaseServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        if (id == null) {
            String url = "/web/listBookServlet";
            resp.sendRedirect(url);
            return;
        }
        Book book = BookDB.getBook(id);
        HttpSession session = req.getSession();
        List<Book> cart = (List) session.getAttribute("cart");
        if (cart == null) {
            cart = new ArrayList<Book>();
            session.setAttribute("cart", cart);
        }
        cart.add(book);
        Cookie cookie = new Cookie("JSESSIONID", session.getId());
        cookie.setMaxAge(60*30);
        cookie.setPath("/web");
        resp.addCookie(cookie);
        String url="/web/cartServlet";
        resp.sendRedirect(url);
    }
}
